package com.Limiter;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * @Package: com.Limiter
 * @ClassName: TokenBucketRateLimiter
 * @Author: h2cloud
 * @CreateTime: 2024/3/16 11:43 下午
 * @Description:
 */
@Slf4j
public class TokenBucketRateLimiter implements Limiter {
	private final long capacity; // 桶的容量
	private final long rate; // 令牌生成速率（每秒生成的令牌数量）
	private long tokens; // 当前桶中的令牌数量
	private long lastRefillTime; // 上次令牌生成时间

	public TokenBucketRateLimiter(long capacity, long rate) {
		this.capacity = capacity;
		this.rate = rate;
		this.tokens = 0;
		this.lastRefillTime = System.currentTimeMillis();
	}

	public synchronized boolean tryAcquire() {
		long currentTime = System.currentTimeMillis();
		long tokensToAdd = (currentTime - lastRefillTime) * rate / 1000;
		System.out.println("tokensToAdd " + tokensToAdd + " tokens " + tokens);
		tokens = Math.min(capacity, tokens + tokensToAdd);
		if (tokens > 0) {
			tokens--;
			lastRefillTime = currentTime;
			return true; // 允许请求
		} else {
			return false; // 桶中没有足够的令牌，拒绝请求
		}
	}

	public static void main(String[] args) throws InterruptedException {
		TokenBucketRateLimiter rateLimiter = new TokenBucketRateLimiter(10, 5);
		Thread.sleep(1000);
		// 模拟请求
		for (int i = 0; i < 1000; i++) {
			log.info("Allow Request: " + rateLimiter.tryAcquire());
			int i1 = new Random().nextInt(120);
			Thread.sleep(i1); // 模拟请求间隔时间
		}
	}
}

